<template>
  <div>
    <div>
      <el-input style="width: 200px; margin: 0 5px" placeholder="标题" v-model="title"></el-input>
      <el-button type="primary" @click="newsList(1)">查询</el-button>
      <el-button type="danger" @click="resetting">重置</el-button>
    </div>
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>
    <el-table :data="tableData" stripe :header-cell-style="{backgroundColor: 'aliceblue' , color: '#666'}"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="序号" align="center"></el-table-column>
      <el-table-column prop="title" label="标题" align="center"></el-table-column>
      <el-table-column prop="desciption" label="简介" align="center"></el-table-column>
      <el-table-column prop="content" label="内容" align="center">
        <template v-slot="scope">
          <el-button @click="showContent(scope.row.content)" size="mini">显示内容</el-button>
          <el-button @click="$router.push('/newsDetail?id=' +scope.row.id)" size="mini">详情页</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="author" label="发布人" align="center"></el-table-column>
      <el-table-column prop="time" label="发布时间" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template v-slot="scope">
          <el-button type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" plain @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageIndex"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog title="新闻信息" :visible.sync="AddDialogFormVisible" width="60%" @close="closeDialog"
               :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="80px" style="margin-right: 20px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="标题"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="desciption">
          <el-input v-model="form.desciption" placeholder="简介"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <!--          <el-input v-model="form.content" placeholder="内容"></el-input>-->
          <div id="editor"></div>
        </el-form-item>
        <div style="text-align: center; margin-bottom: 20px">
          <el-button type="primary" @click="AddDialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </el-form>
    </el-dialog>

    <el-dialog title="查看内容" :visible.sync="AddDialogFormVisible1" width="60%">
      <el-card class="w-e-text">
        <div v-html="content"></div>
      </el-card>
      <div style="text-align: center;margin-top: 20px">
        <el-button type="primary" @click="AddDialogFormVisible1 = false">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import E from "wangeditor"
import hljs from 'highlight.js'

export default {
  name: "News",
  data() {
    return {
      tableData: [], // 所有的数据
      pageIndex: 1, // 当前的页码
      pageSize: 5, // 每页显示的个数
      title: '', // 分页查询的用户名
      total: 0, // 数据的总条数
      AddDialogFormVisible: false,
      user: JSON.parse(localStorage.getItem('power-user') || '{}'), // 存储缓存
      form: {}, // 存储表单缓存
      rules: {
        title: [{required: true, message: '请输入标题', trigger: 'blur'},],
        // desciption: [{required: true, message: '请输入标题', trigger: 'blur'},],
        // content: [{required: true, message: '请输入内容', trigger: 'blur'},],
      },
      ids: [],
      editor: null,
      content: '',
      AddDialogFormVisible1: false,
    }
  },
  created() {
    this.newsList()
  },
  methods: {
    showContent(content) { // 查看内容
      this.content = content
      this.AddDialogFormVisible1 = true // 打开弹窗
    },
    // 弹窗关闭前的回调
    closeDialog() {
      // 销毁编辑器
      this.editor.destroy()
      this.editor = null
    },
    // 批量删除
    delBatch() {
      if (!this.ids.length) {
        this.$message.warning("请选择要删除的数据")
        return
      }
      // 二次确认
      this.$confirm('您确认删除这些数据吗？', '确认删除', {type: 'warning'}).then(res => {
        this.$request.delete('/news/delete/batch', {data: this.ids}).then(res => {
          if (res.code === '200') {
            this.$message.success("操作成功")
            this.newsList(1)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
      })
    },
    handleSelectionChange(rows) { // 当前选中行的所有数据
      console.log(rows)
      this.ids = rows.map(v => v.id)
      // console.log(ids)
    },
    // 单个删除
    del(id) {
      // 二次确认
      this.$confirm('您确认删除吗？', '确认删除', {type: 'warning'}).then(res => {
        this.$request.delete('/news/delete/' + id).then(res => {
          if (res.code === '200') {
            this.$message.success("操作成功")
            this.newsList(1)
          } else {
            this.$message.error(res.msg)
          }
        })
      }).catch(() => {
      })
    },

    // 设置富文本的一些配置
    setRichText() {
      // #editor 就表示上面弹窗里的id="editor"
      this.$nextTick(() => {
        this.editor = new E(`#editor`) // 初始化富文本区域
        this.editor.highlight = hljs
        this.editor.config.uploadImgServer = 'http://localhost:8888/file/editor/upload'
        this.editor.config.uploadFileName = 'file' // 这里对应后台的返回的对象
        this.editor.config.uploadImgHeaders = {
          token: this.user.token
        }
        this.editor.config.uploadImgParams = {
          type: 'img'
        }
        this.editor.config.uploadVideoServer = 'http://localhost:8888/file/editor/upload'
        this.editor.config.uploadVideoName = 'file' // 这里对应后台的返回的对象
        this.editor.config.uploadVideoHeaders = {
          token: this.user.token
        }
        this.editor.config.uploadVideoParams = {
          type: 'video'
        }
        this.editor.create() // 创建
      })
    },
    handleEdit(row) { // 编辑数据
      // 给form对象赋值，注意要深拷贝数据
      this.form = JSON.parse(JSON.stringify(row))
      // 打开弹窗
      this.AddDialogFormVisible = true
      this.setRichText() // 调用富文本上传配置
      // setTimeout延时加载，等里面的内容加载好
      setTimeout(() => {
        this.editor.txt.html(row.content) // 设置富文本内容
      }, 0)
    },
    handleAdd() { // 新增数据
      this.form = {}  // 新增数据的时候清空数据
      this.AddDialogFormVisible = true // 打开弹窗
      // #editor 就表示上面弹窗里的id="editor"
      this.setRichText() // 调用富文本上传配置
    },
    save() { // 保存按钮触发的逻辑 它会触发新增或者修改
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          // 获取编辑框的内容
          let content = this.editor.txt.html()
          this.form.content = content
          this.$request({
            // 因为修改是从行内元素拿到的，有id，因此可以作此判断
            // 判断有没id，如果有id说明是修改的方法，如果没有则是新增的方法
            method: this.form.id ? 'POST' : 'POST',
            url: this.form.id ? '/news/update' : '/news/add',
            data: this.form
          }).then(res => {
            if (res.code === '200') {
              this.$message.success('保存成功')
              this.newsList(1)
              this.AddDialogFormVisible = false
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },

    resetting() {
      this.title = ''
      this.newsList()
    },
    newsList(pageIndex) { // 分页查询
      if (pageIndex) {
        this.pageIndex = pageIndex
      }
      request.get('/news/selectByPage', {
        params: {
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
          title: this.title,
        }
      }).then(res => {
        if (res.code == '200') {
          this.tableData = res.data.records
          this.total = res.data.total
        }
      })
    },
    handleCurrentChange(pageIndex) {
      // 赋值
      this.pageIndex = pageIndex
      // 调用分页查询方法
      this.newsList()
    }
  },
}
</script>

<style scoped>
/deep/ .avatar-uploader {
  border-radius: 50%;
}

/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border-radius: 50%;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 50%;
}
</style>